#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re
from typing import List, Dict
from .base import FilterRule

class ListStyleChangeFilter(FilterRule):
    """列表样式变化过滤规则"""
    
    def __init__(self):
        # 无序列表符号集合
        self.unordered_symbols = {'- ', '* ', '+ '}
        
        # 有序列表数字模式
        self.ordered_list_pattern = r'^\d+[.)]\s+'
    
    def should_filter(self, add_content: str, remove_content: str, hunk_changes: List[Dict]) -> bool:
        """判断是否为列表样式变化"""
        add_clean = add_content.strip()
        remove_clean = remove_content.strip()
        
        if add_clean == remove_clean:
            return False
        
        if self._is_unordered_list_change(add_clean, remove_clean):
            return True
        
        if self._is_ordered_list_change(add_clean, remove_clean):
            return True
        
        return False
    
    def _is_unordered_list_change(self, add_content: str, remove_content: str) -> bool:
        """检查是否为无序列表符号变化"""
        add_starts_with_symbol = any(add_content.startswith(sym) for sym in self.unordered_symbols)
        remove_starts_with_symbol = any(remove_content.startswith(sym) for sym in self.unordered_symbols)
        
        if not (add_starts_with_symbol and remove_starts_with_symbol):
            return False
        
        add_symbol = add_content[:2]
        remove_symbol = remove_content[:2]
        
        # 内容相同且仅符号不同
        if add_content[2:].strip() == remove_content[2:].strip() and add_symbol != remove_symbol:
            return True
        
        return False
    
    def _is_ordered_list_change(self, add_content: str, remove_content: str) -> bool:
        """检查是否为有序列表符号变化"""
        add_match = re.match(self.ordered_list_pattern, add_content)
        remove_match = re.match(self.ordered_list_pattern, remove_content)
        
        if not (add_match and remove_match):
            return False
        
        add_number = re.match(r'^\d+', add_content).group()
        remove_number = re.match(r'^\d+', remove_content).group()
        
        if add_number == remove_number:
            add_symbol = add_content[len(add_number)]
            remove_symbol = remove_content[len(remove_number)]
            # 文本一致，仅 . 与 ) 不同
            add_rest = add_content[len(add_number)+1:].strip()
            remove_rest = remove_content[len(remove_number)+1:].strip()
            return add_rest == remove_rest and add_symbol in '.)' and remove_symbol in '.)' and add_symbol != remove_symbol
        
        return False
    
    def get_filter_reason(self) -> str:
        return "list_style_change" 